package com.fishingwithme.android.ui.activities

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.rememberNavController
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.navigation.FishingNavHost
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.theme.FishingWithMeTheme
import com.fishingwithme.android.ui.viewmodels.AuthViewModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * 登录Activity，作为应用的启动入口，检查登录状态并决定显示登录界面或主界面
 */
@AndroidEntryPoint
class LoginActivity : ComponentActivity() {

    @Inject
    lateinit var preferencesManager: PreferencesManager

    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val themeMode by preferencesManager.getThemeMode().collectAsState(
                initial = PreferencesManager.THEME_FOLLOW_SYSTEM
            )

            FishingWithMeTheme(themeMode = themeMode) {
                val authViewModel: AuthViewModel = hiltViewModel()
                val authUiState by authViewModel.uiState.collectAsState()
                val navController = rememberNavController()

                // Check login status and navigate accordingly
                LaunchedEffect(authUiState.isLoggedIn) {
                    if (authUiState.isLoggedIn) {
                        // If already logged in, navigate to MainActivity
                        // This ensures the user sees the main interface with bottom navigation
                        val intent = android.content.Intent(
                            this@LoginActivity,
                            com.fishingwithme.android.MainActivity::class.java
                        )
                        startActivity(intent)
                        finish() // Close LoginActivity
                    }
                }

                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    // Show login screen
                    FishingNavHost(
                        navController = navController,
                        startDestination = FishingNavigation.LOGIN
                    )
                }
            }
        }
    }
}